<template>
  <div v-if="showButton">
    <template v-if="pickingType === 'single'">
      <el-button :type="pickingOrderData.tracking_number !== '' ? 'success' : 'danger'" :disabled="isButtonDisabled" @click="showDialog" :loading="printLoading">
        {{ $t('order.downloadShipping') }}
      </el-button>
    </template>

    <template v-if="pickingType === 'all'">
      <el-button :type="pickingOrderData.status === 1 ? 'success' : 'danger'"  @click="showDialog" :loading="printLoading" :disabled="isButtonAllDisabled">
        {{ $t('order.downloadShipping') }}
      </el-button>
    </template>

    <el-dialog :title="$t('选择物流商')" :visible.sync="dialog" width="500px" style="text-align: left" :append-to-body="true">
      <template>
        <el-radio v-for="(item, index) in integratedLogisticsSettingData" :key="index" v-model="getDefaultLogisticsType" :label="item.logistics_type">
          {{ item.logistics_type }}
        </el-radio>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="printShipping(getDefaultLogisticsType)" :loading="loading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { printLogisticsPickShipping,printAllLogisticsPickShipping } from '@/api/picking';

export default {
  name: 'LogisticsPickingButton',
  props: {
    pickingType: {
      // 判断是多个还是单个
      type: String
    },
    pickingOrderData: {
      type: Object
    },
    integratedLogisticsSettingData: {
      type: Array
    },
    defaultLogisticsType: {
      type: String
    },
    pickingLogisticsType: {
      type: Number
    },

    isButtonDisabled: {
      type: Boolean,
      default: false
    },
    isButtonAllDisabled:{
      type:Boolean,
      default: false

    }

  },
  computed: {
    showButton() {
      if (this.pickingType === 'single') {
        // 在单个订单的情况下 判断是否开启物流配置 且 是否有物流面单了
        if (this.integratedLogisticsSettingData.length <= 0 && this.pickingOrderData.tracking_number === '') {
          // 不存在已经下载的情况 不显示
          return false;
        }

        // 判断是否为手动传递快递单号
        if (this.pickingOrderData.forLogisticsTrackingNumberForOrderData.id > 0) {
          if (this.pickingOrderData.forLogisticsTrackingNumberForOrderData.is_manual_operation === 1) {
            return false;
          }
        }
      }

      if (this.pickingType === 'all') {
        if (this.integratedLogisticsSettingData.length <= 0 && this.pickingOrderData.status !== 1) {
          return false;
        }
        if (this.pickingOrderData.manualOperationInfo === false) {
          return false;
        }
      }

      // 不是物流面单拣货单 不显示
      if (this.pickingLogisticsType !== 2) {
        return false;
      }
      return true;
    }
  },
  data() {
    return {
      dialog: false,
      loading: false,
      printLoading: false,
      getDefaultLogisticsType: ''
    };
  },
  created() {
    this.getDefaultLogisticsType = this.defaultLogisticsType;
  },
  methods: {
    showDialog() {
      this.getDefaultLogisticsType = this.defaultLogisticsType;

      let successInfo = false;
      if (this.pickingType === 'single') {
        if (this.pickingOrderData.tracking_number !== '') {
          successInfo = true;
        }
      }
      if (this.pickingType === 'all') {
        if (this.pickingOrderData.status === 1) {
          successInfo = true;
        }
      }

      if (successInfo) {
        this.printShipping();
        return false;
      }

      if (this.integratedLogisticsSettingData.length <= 0) {
        return false;
      } else if (this.integratedLogisticsSettingData.length === 1) {
        this.printShipping();
      } else {
        this.dialog = true;
      }
    },

    // 打印面单
    printShipping(logisticsType = '') {
      this.loading = true;
      this.printLoading = true;
        this.$emit('closeLableDialogVisible', false);
      const postData = {
        logisticsType: logisticsType,
        pickingType: this.pickingType,
        pickingInfo: this.pickingOrderData
      };
      //下载全部面单的时候只加入队列不做处理
      if (this.pickingType === 'all'&&this.pickingOrderData.status ==0) {
        printAllLogisticsPickShipping(postData).then((res) => {
          this.loading = false;
          this.printLoading = false;
          this.dialog = false;
          if(this.$parent.lableDialog){
            this.$parent.lableDialog();
          }else{
            this.$emit('lableDialog',this.pickingOrderData);
          }

         });
      } else {
        //下载面单
        printLogisticsPickShipping(postData).then((res) => {
          this.loading = false;
          this.printLoading = false;
          console.log(res);
          if (res.headers['content-type'].match(/application\/pdf/) && res.status === 200) {
            this.loading = false;
            this.printLoading = false;
            const pdfFile = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
            // 跳转页面预览
            window.open(pdfFile);
            // 60秒后释放
            setTimeout(() => {
              URL.revokeObjectURL(pdfFile); //释放URL对象
            }, 60000);

            this.$emit('changeOrder', true);
          } else {
            if (res.headers['content-type'].match(/application\/json/)) {
              // 创建一个FileReader对象
              const reader = new FileReader();

              // 定义一个回调函数，处理读取完成后的操作
              reader.onload = (event) => {
                // event.target.result 包含了Blob对象的内容作为字符串
                let blobAsText = event.target.result;

                // 在这里，你可以处理blobAsText，比如将其显示在页面上或执行其他操作
                const data = JSON.parse(blobAsText);
                console.log(data);
                if (data.error === 210) {
                  this.$message({
                    showClose: true,
                    message: data.message,
                    type: 'error',
                    duration: 6000
                  });
                } else {
                  this.$errorMessage(data.message);
                  this.$emit('changeOrder', true);
                  return false;
                }
              };

              // 开始读取Blob对象并以文本形式返回

              reader.readAsText(res.data);
            } else {
              this.$errorMessage('服务繁忙请稍后再试');
              return false;
            }
          }
        });
      }
    }
  }
};
</script>

<style scoped lang="scss"></style>
